﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;

namespace ReportGenerators.QuanLyKho
{
    public partial class FrmThongKeChuyenKho : BasicForms.FrmSupportPrintableComponents
    {
        public FrmThongKeChuyenKho()
        {
            InitializeComponent();
        }

        private void FrmThongKeNhapXuatTon_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedIndex = 19;

                cmbKhoXuat.DataSource = GeneralLibs.SortDataAlphabetic.DataTableSort(DanhMucKho.Instance.DataTable, "Ten", 0).DefaultView;
                cmbKhoXuat.DisplayColumn = "Ten";
                cmbKhoXuat.ValueColumn = "ID";
                cmbKhoXuat.AddVisibleColumn("Ma", "Mã");
                cmbKhoXuat.AddVisibleColumn("Ten", "Tên");
                cmbKhoXuat.EditValue = Guid.Empty;

                cmbKhoNhap.DataSource = GeneralLibs.SortDataAlphabetic.DataTableSort(DanhMucKho.Instance.DataTable, "Ten", 0).DefaultView;
                cmbKhoNhap.DisplayColumn = "Ten";
                cmbKhoNhap.ValueColumn = "ID";
                cmbKhoNhap.AddVisibleColumn("Ma", "Mã");
                cmbKhoNhap.AddVisibleColumn("Ten", "Tên");
                cmbKhoNhap.EditValue = Guid.Empty;

                gridControl.DataSource = dsThongKeChuyenKho.Detail;
                gridControlDsVatTuHangHoa.DataSource = dsThongKeChuyenKho.VatTuHangHoa;

                dsThongKeChuyenKho.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());
            }
            catch (Exception ex)
            {
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                if (column.FieldName == "So" || column.FieldName == "Ngay")
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                else
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }
            try
            {
                chkChooseAllVatTuHangHoa.Checked = false;
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeChuyenKho.VatTuHangHoa.Rows)
            {
                row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
            }
        }

        private void cmbKhoXuat_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKhoXuat.EditValue = Guid.Empty;
        }

        private void cmbKhoNhap_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKhoNhap.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if(!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            BasicForms.FrmProgressBarDev.StartShowProgress();
            try
            {
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;

                string vatTuHangHoaCondition = "1 = 1";
                if (!chkChooseAllVatTuHangHoa.Checked)
                {
                    vatTuHangHoaCondition = "B.VatTuHangHoa1ID IN  (";
                    foreach (DataRow row in dsThongKeChuyenKho.VatTuHangHoa.Rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                    else vatTuHangHoaCondition = "1 = 0";
                }


                string khoCondition = "1 = 1";
                if (cmbKhoXuat.EditValue != null && (Guid)cmbKhoXuat.EditValue != Guid.Empty)
                    khoCondition += string.Format("AND A.Kho1ID = '{0}'", cmbKhoXuat.EditValue);
                if (cmbKhoNhap.EditValue != null && (Guid)cmbKhoNhap.EditValue != Guid.Empty)
                    khoCondition += string.Format("AND A.Kho2ID = '{0}'", cmbKhoNhap.EditValue);

                cmd.CommandText = string.Format("SELECT A.So, A.Ngay, A.TenNguoiThucHien Ten, D.Ten KhoXuat, E.Ten KhoNhap, \n"+
		                                        "       F.Ma MaHangHoa, F.Ten TenHangHoa, F.DonViTinh, F.GiaBia GiaBanLe, \n"+
		                                        "       B.Value1 SoLuong, B.Value2 DonGia, B.Value3 ThanhTien, B.Text5 GhiChu \n"+
                                                "FROM ChungTu A INNER JOIN KhoanMucChungTu B ON A.ChungTuID = B.ChungTuID \n"+
                                                "               INNER JOIN LoaiChungTu C ON A.LoaiChungTuID = C.ID AND C.Ma = N'PhieuChuyenKho' \n"+
                                                "               INNER JOIN Kho D ON A.Kho1ID = D.ID \n"+
                                                "               INNER JOIN Kho E ON A.Kho2ID = E.ID \n" +
                                                "               INNER JOIN VatTuHangHoa F ON B.VatTuHangHoa1ID = F.ID \n" +
                                                "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi \n" +
                                                "	AND	{0} \n" +
                                                "	AND {1} \n" +
                                                "ORDER BY A.Ngay",
                                                vatTuHangHoaCondition, khoCondition);

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                dsThongKeChuyenKho.Detail.Clear();
                da.Fill(dsThongKeChuyenKho.Detail);

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            string more1 = "";
            if ((cmbKhoXuat is Guid) && (Guid)cmbKhoXuat.EditValue != Guid.Empty) 
                more1 = string.Format("Kho xuất: {0}", DanhMucKho.Instance.GetByID((Guid)cmbKhoXuat.EditValue).Ten);
            if ((cmbKhoNhap is Guid) && (Guid)cmbKhoNhap.EditValue != Guid.Empty) 
                more1 = string.Format(" Kho nhập: {0}", DanhMucKho.Instance.GetByID((Guid)cmbKhoNhap.EditValue).Ten);
            PrintWithHeader(true, gridControl, true, true, "Thống kê chuyển kho", more1);
        }
    }
}
